package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocal;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    //引入自动审核业务的接口
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    //kafka模板类
    @Resource
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //1. 参数校验
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();

        //2. 执行分页查询
        IPage<WmNews> ipage = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();

        //2.1 状态过滤
        if (dto.getStatus() != null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }

        //2.2 发布时间
        if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null){
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubdate(),dto.getEndPubdate());
        }

        //2.3 关键字
        if (StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        //2.4 频道
        if (dto.getChannelId() != null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        //2.5 当前用户
        queryWrapper.eq(WmNews::getUserId, WmThreadLocal.getWmUser().getId());

        ipage = page(ipage,queryWrapper);

        //3.封装数据
        ResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(), (int) ipage.getTotal());
        result.setData(ipage.getRecords());

        //4.返回数据

        return result;
    }

    /**
     * 文章发布、修改、保存草稿---主方法
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult submit(WmNewsDto dto) {
        //1. 参数校验
        if(dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.修改和保存的方法
        WmNews wmnews = new WmNews();
        BeanUtils.copyProperties(dto,wmnews);
        //封装数据userid
        wmnews.setUserId(WmThreadLocal.getWmUser().getId());
        wmnews.setCreatedTime(new Date());
        //解决格式
        List<String> images = dto.getImages();
        if (images.size()>0 && images != null){
            String image = StringUtils.join(images, ".");
            wmnews.setImages(image);
        }

        saveOrUpdateWnews(wmnews);

        //3. 判断是否为草稿，如果为草稿，则以下步骤不再执行
        if (dto.getStatus() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DRAFT_EXIST);
        }

        //3.1 把内容中content里面的图片给抽取出来
        List<String> imageList = extractImageList(wmnews);

        //4.关联内容中的图片与文章的关系，操作wm_news_marterial表，批量新增中间表
          //4.2 要把图片地址集合转化成地址所对应的素材id,根据图片地址去查询wm_material表从而获取对应的素材id
        contentImageToNews(wmnews,imageList,0);

        //5. 关联封面中的图片与文章的关系，操作wm_news_marterial表
          //5.1 判断封面是否是自动
        //返回值一定此时是空的
        coverImageToNews(dto,wmnews,imageList);

        //6. 执行异步调用自动审核业务
        //wmNewsAutoScanService.autoScanWmNews(wmnews.getId());

        //改成调用延迟服务添加任务的方法,同样也是异步操作
        wmNewsTaskService.addNewsToTask(wmnews.getId(),wmnews.getPublishTime());

        return ResponseResult.okResult("发布成功");
    }

    /**
     * 封面图片与文章的关系
     * @param dto
     * @param wmnews
     * @param imageList
     */
    private void coverImageToNews(WmNewsDto dto, WmNews wmnews, List<String> imageList) {
        List<String> coverImages = dto.getImages();
        if (dto.getType() == null){
            //内容中的图片个数大于等于1小于3，此时我们认为是单图
            if (imageList.size()>1 && imageList.size()<3){
                coverImages = imageList.stream().limit(1).collect(Collectors.toList());
                wmnews.setType((short) 1);
            }else if (imageList.size() >= 3){//多图
                coverImages = imageList.stream().limit(3).collect(Collectors.toList());
                wmnews.setType((short) 3);
            }else {//内容中也没有图片，我们认为无图
                wmnews.setType((short) 0);
            }
            wmnews.setImages(StringUtils.join(coverImages,","));
            updateById(wmnews);
        }
        //批量新增中间表
        contentImageToNews(wmnews,coverImages,1);
    }

    /**
     * 抽取的方法三，内容图片与文章的关系
     * @param wmnews
     * @param imageList
     * @param type
     */
    private void contentImageToNews(WmNews wmnews, List<String> imageList, Integer type) {
        if (imageList.size()>0 && imageList !=null){
            //根据图片地址集合获取素材集合
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageList));
            //stream流获取素材id集合
            List<Integer> materialIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //4.1 调用mapper接口
            wmNewsMaterialMapper.saveBatch(materialIds,wmnews.getId(),type);

        }
    }


    /**
     * 抽取的第二个方法，获取文本内容中的图片地址集合
     * @param wmnews
     * @return
     */
    private List extractImageList(WmNews wmnews) {
        List<String> imageUrlList = new ArrayList<>();

        //获取内容
        String content = wmnews.getContent();
        //2.转化类型格式，list嵌套map格式
        List<Map> mapList = JSON.parseArray(content, Map.class);
        //3.从map中获取type=image的value值
        for (Map map : mapList) {
            if (map.get("type").equals("image")){
                String imageUrl = (String) map.get("value");
                imageUrlList.add(imageUrl);
            }
        }
        return imageUrlList;
    }

    /**
     * 抽取的第一个方法，修改和保存文章
     */
    private void saveOrUpdateWnews(WmNews wmNews){
        //修改
        if (wmNews.getId() != null){
            //删除中间表
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));

            //修改文章表
            updateById(wmNews);
        }else {
            //新增
            save(wmNews);
        }
    }

    /**
     * 文章上下架功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //参数校验
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据文章id判断当前文章是否存在
        WmNews wmNews = getById(dto.getId());
        //如果不存在，则返回报错信息
        if (wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //如果存在，则查询状态是不是发布状态
        if (wmNews.getStatus() != WmNews.Status.PUBLISHED.getCode()){
            //如果不是，则返回报错信息
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"此文章状态不是发布状态，不可以上下架操作");
        }
        //如果是，则修改文章状态
        wmNews.setEnable(dto.getEnable());
        boolean flag = updateById(wmNews);
        if (!flag){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"修改状态不成功");
        }

        //发送消息内容
        if(wmNews.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"articleId为空,不能发送消息");
        }

        Map map = new HashMap();
        map.put("articleId",wmNews.getArticleId());
        map.put("enable",wmNews.getEnable());
        kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));

        return ResponseResult.okResult("修改状态成功");
    }

}
